package com.example.homework9;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class storageexternal extends Fragment {
    String FILE_NAME = "external_data";
    public storageexternal() {
        super(R.layout.storageexternal);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Button writeExternalButton = getView().findViewById(R.id.writeExternalButton);
        writeExternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath = getActivity().getExternalFilesDir(null);
                File file = new File(externalPath,FILE_NAME);
                try {
                    FileOutputStream outputStream = new FileOutputStream(file);
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
                    writer.write("Tom");
                    writer.close();
                    Toast.makeText(getActivity(),"写入成功",Toast.LENGTH_SHORT).show();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Button readExternalButton = getView().findViewById(R.id.readExternalButton);
        readExternalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalPath = getActivity().getExternalFilesDir(null);
                File file = new File(externalPath,FILE_NAME);
                try {
                    FileInputStream inputStream = new FileInputStream(file);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line = reader.readLine();
                    Toast.makeText(getActivity(),line,Toast.LENGTH_SHORT).show();
                    inputStream.close();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
